<script setup lang="ts" name="Post">
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { downloadBlobFile, warnBox } from '@/utils'
import { listPost, postExport, delPost } from '@/api/system/post/index'
import type { QueryParams, PostItem } from '@/api/system/post/type'
import { ElMessage } from 'element-plus'
import EditDialog from './components/EditDialog.vue'
import { debounce } from 'es-toolkit'
import { formatDate } from '@/utils/day'

const formValue = ref<QueryParams>({
	postCode: '',
	postName: '',
	status: ''
})

const sysNormalDisable = ref<IGetDictsRes>([])

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '岗位编码',
		prop: 'postCode'
	},
	{
		type: 'input',
		label: '岗位名称',
		prop: 'postName'
	},
	{
		type: 'select',
		label: '岗位状态',
		prop: 'status',
		options: sysNormalDisable as unknown as any,
		attrs: {
			style: 'width: 200px'
		}
	}
])
// 表格数据
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<PostItem[]>([])
const selectedRows = ref<PostItem[]>([])

// 多选和单选控制
const multiple = computed(() => selectedRows.value.length < 1)

const columns = ref<TableColums[]>([
	{
		type: 'selection',
		width: 50,
		align: 'center'
	},
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '岗位编号',
		prop: 'id'
	},
	{
		label: '岗位编码',
		prop: 'postCode'
	},
	{
		label: '岗位名称',
		prop: 'postName'
	},
	{
		label: '岗位排序',
		prop: 'postSort',
		align: 'center'
	},
	{
		label: '状态',
		prop: 'status',
		align: 'center'
	},
	{
		label: '创建时间',
		prop: 'createTime'
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 160,
		align: 'center'
	}
])

// 对话框
const editDialogRef = useTemplateRef('editDialogRef')

// 选择变化处理
const handleSelectionChange = (selection: PostItem[]) => {
	selectedRows.value = selection
}

// 获取表格数据
const getTableData = async () => {
	loading.value = true
	try {
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		}
		const res = await listPost(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}

// 新增
const handleAdd = () => {
	editDialogRef.value?.init('add')
}

// 修改
const handleEdit = (row: PostItem) => {
	editDialogRef.value?.init('edit', row)
}

// 删除
const handleDelete = async (row?: PostItem) => {
	let ids: string
	let message: string

	if (row) {
		ids = String(row.id)
		message = `是否确认删除岗位编号为"${ids}"的数据项？`
	} else {
		ids = selectedRows.value.map(item => item.id).join(',')
		message = `是否确认删除选中的${selectedRows.value.length}条数据？`
	}

	await warnBox({
		message: message
	})

	try {
		await delPost(ids)
		ElMessage.success('删除成功')
		getTableData()
	} catch (error) {
		console.error('删除失败:', error)
		ElMessage.error('删除失败，请重试')
	}
}

// 删除选中的
const handleDeleteSelected = async () => {
	if (selectedRows.value.length > 0) {
		await handleDelete()
	}
}
const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

// 导出
const exportFn = async () => {
	try {
		const params = { ...formValue.value }
		const data = await postExport(params)
		downloadBlobFile(data.data, data.filename || `post_${new Date().getTime()}.xlsx`)
	} catch (error) {
		console.error('导出失败:', error)
		ElMessage.error('导出失败，请重试')
	}
}

// 初始化
const init = () => {
	getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
		console.log('sysNormalDisable:', sysNormalDisable.value)
	})
}

onMounted(() => {
	init()
	getTableData()
	// js操作 最后一个.el-col 去除 .el-col-0这个类名
	const lastCol = document.querySelector('.el-col:last-child')
	if (lastCol) {
		lastCol.classList.remove('el-col-0')
	}
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				:model="formValue"
				:inline="true"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
				@selectionChange="handleSelectionChange"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['system:post:add'])"
						type="primary"
						@click="handleAdd"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['system:post:remove'])"
						:disabled="multiple"
						@click="handleDeleteSelected"
					>
						删除
					</el-button>
					<el-button
						v-if="checkPermission(['system:post:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
				</template>
				<template #status="{ row }">
					<DictTag
						:options="sysNormalDisable"
						:value="row.status"
					/>
				</template>
				<template #createTime="{ row }">
					{{ formatDate(row.createTime) }}
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:post:edit'])"
						type="primary"
						link
						@click="handleEdit(row)"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['system:post:remove'])"
						type="danger"
						link
						@click="handleDelete(row)"
					>
						删除
					</el-button>
				</template>
			</QTable>
		</div>
		<EditDialog
			ref="editDialogRef"
			@refresh="getTableData"
		/>
	</div>
</template>
